<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="baidu-site-verification" content="zD47G9xe42" />


<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="uiste个人博客网站,uiste,uiste博客,PHP,运维,Hexo,技术博客" />





  <link rel="alternate" href="/atom.xml" title="uiste" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="Stay Hungry，Stay Foolish">
<meta property="og:type" content="website">
<meta property="og:title" content="uiste">
<meta property="og:url" content="http://blog.uiste.com/page/3/index.html">
<meta property="og:site_name" content="uiste">
<meta property="og:description" content="Stay Hungry，Stay Foolish">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="uiste">
<meta name="twitter:description" content="Stay Hungry，Stay Foolish">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://blog.uiste.com/page/3/"/>

  <title>
 
  uiste - Stay Hungry，Stay Foolish 

</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?b58b87af012832b8ae35e33bb45b44fa";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left 
   page-home 
 ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">uiste</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">uiste个人博客</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      

            <li class="menu-item menu-item-search"> <a title="把这个链接拖到你的Chrome收藏夹工具栏中" href='javascript:(function() {
    function c() {
        var e = document.createElement("link");
        e.setAttribute("type", "text/css");
        e.setAttribute("rel", "stylesheet");
        e.setAttribute("href", f);
        e.setAttribute("class", l);
        document.body.appendChild(e)
    }
 
    function h() {
        var e = document.getElementsByClassName(l);
        for (var t = 0; t < e.length; t++) {
            document.body.removeChild(e[t])
        }
    }
 
    function p() {
        var e = document.createElement("div");
        e.setAttribute("class", a);
        document.body.appendChild(e);
        setTimeout(function() {
            document.body.removeChild(e)
        }, 100)
    }
 
    function d(e) {
        return {
            height : e.offsetHeight,
            width : e.offsetWidth
        }
    }
 
    function v(i) {
        var s = d(i);
        return s.height > e && s.height < n && s.width > t && s.width < r
    }
 
    function m(e) {
        var t = e;
        var n = 0;
        while (!!t) {
            n += t.offsetTop;
            t = t.offsetParent
        }
        return n
    }
 
    function g() {
        var e = document.documentElement;
        if (!!window.innerWidth) {
            return window.innerHeight
        } else if (e && !isNaN(e.clientHeight)) {
            return e.clientHeight
        }
        return 0
    }
 
    function y() {
        if (window.pageYOffset) {
            return window.pageYOffset
        }
        return Math.max(document.documentElement.scrollTop, document.body.scrollTop)
    }
 
    function E(e) {
        var t = m(e);
        return t >= w && t <= b + w
    }
 
    function S() {
        var e = document.createElement("audio");
        e.setAttribute("class", l);
        e.src = i;
        e.loop = false;
        e.addEventListener("canplay", function() {
            setTimeout(function() {
                x(k)
            }, 500);
            setTimeout(function() {
                N();
                p();
                for (var e = 0; e < O.length; e++) {
                    T(O[e])
                }
            }, 15500)
        }, true);
        e.addEventListener("ended", function() {
            N();
            h()
        }, true);
        e.innerHTML = " <p>If you are reading this, it is because your browser does not support the audio element. We recommend that you get a new browser.</p> <p>";
        document.body.appendChild(e);
        e.play()
    }
 
    function x(e) {
        e.className += " " + s + " " + o
    }
 
    function T(e) {
        e.className += " " + s + " " + u[Math.floor(Math.random() * u.length)]
    }
 
    function N() {
        var e = document.getElementsByClassName(s);
        var t = new RegExp("\\b" + s + "\\b");
        for (var n = 0; n < e.length; ) {
            e[n].className = e[n].className.replace(t, "")
        }
    }
 
    var e = 30;
    var t = 30;
    var n = 350;
    var r = 350;
    var i = "//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake.mp3";
    var s = "mw-harlem_shake_me";
    var o = "im_first";
    var u = ["im_drunk", "im_baked", "im_trippin", "im_blown"];
    var a = "mw-strobe_light";
    var f = "//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css";
    var l = "mw_added_css";
    var b = g();
    var w = y();
    var C = document.getElementsByTagName("*");
    var k = null;
    for (var L = 0; L < C.length; L++) {
        var A = C[L];
        if (v(A)) {
            if (E(A)) {
                k = A;
                break
            }
        }
    }
    if (A === null) {
        console.warn("Could not find a node of the right size. Please try a different page.");
        return
    }
    c();
    S();
    var O = [];
    for (var L = 0; L < C.length; L++) {
        var A = C[L];
        if (v(A)) {
            O.push(A)
        }
    }
})()    '>High</a> </li>

    </ul>
  

 
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
   
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20161009-1.html" itemprop="url">
                  PHP - MySQL 两表联查 | 显示不同类型
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-09T10:00:38+08:00" content="2016-10-09">
              2016-10-09
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20161009-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20161009-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="两表联查"><a href="#两表联查" class="headerlink" title="两表联查"></a>两表联查</h1><h3 id="需求"><a href="#需求" class="headerlink" title="需求"></a>需求</h3><p>不同商品的属性扩展<br>如：</p>
<blockquote>
<p>音乐：中文片名、英文片名、商品别名、介质/格式、国家地区、导演/指挥、主唱、长度、歌词<br>书：作者、出版社、图书书号、出版日期、图书页数、字数、所属分类<br>等…</p>
</blockquote>
<h3 id="思想"><a href="#思想" class="headerlink" title="思想"></a>思想</h3><p>通过对产品类型划分，使用属性类别<code>(attr_type)</code>表作为中间表，对属性<code>(attribute)</code>扩展连接。</p>
<h3 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//获取attr_type表数据</span></div><div class="line">   <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getAttrTypeList</span><span class="params">()</span></span>&#123;</div><div class="line">       $sql=<span class="string">'select attr_type_name,count(attr_name) as `count` from attr_type natural left join attribute group by attr_type_id'</span>;</div><div class="line">       <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;db-&gt;fetchAll($sql);</div><div class="line">   &#125;</div></pre></td></tr></table></figure>
<h1 id="显示不同类型"><a href="#显示不同类型" class="headerlink" title="显示不同类型"></a>显示不同类型</h1><p>controller<br><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//显示属性</span></div><div class="line">$attr_type_id=<span class="keyword">isset</span>($_GET[<span class="string">'attr_type_id'</span>])?(int)$_GET[<span class="string">'attr_type_id'</span>]:<span class="number">0</span>;</div><div class="line">$attr_model=<span class="keyword">new</span> AttributeModel();</div><div class="line">$attr_list=$attr_model-&gt;getAttrByTypeId($attr_type_id);</div></pre></td></tr></table></figure></p>
<p>model<br><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//通过属性类别id获取属性</span></div><div class="line">   <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getAttrByTypeId</span><span class="params">($attr_type_id)</span></span>&#123;</div><div class="line">       $sql=<span class="string">"select * from attribute natural join attr_type where 1"</span>;</div><div class="line">       <span class="keyword">if</span>($attr_type_id&gt;<span class="number">0</span>)</div><div class="line">           $sql.=<span class="string">" and attr_type_id=$attr_type_id"</span>;</div><div class="line">       $sql.=<span class="string">' order by attr_type_id'</span>;</div><div class="line">       <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;db-&gt;fetchAll($sql);</div><div class="line">   &#125;</div></pre></td></tr></table></figure></p>
<p>view<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">&lt;div class="form-div"&gt;</div><div class="line">  &lt;form action="" name="searchForm"&gt;</div><div class="line">    &lt;img src="/Application/View/Admin/images/icon_search.gif" width="26" height="22" border="0" alt="SEARCH"&gt;</div><div class="line">    按商品类型显示：&lt;select name="goods_type" onchange="location.href='index.php?p=Admin&amp;c=Attribute&amp;a=list&amp;attr_type_id='+this.value"&gt;</div><div class="line">    &lt;option value="0"&gt;所有商品类型&lt;/option&gt;</div><div class="line">    &lt;?php foreach($attr_type_list as $rows):?&gt;</div><div class="line">    	&lt;option value="&lt;?php echo $rows['attr_type_id']?&gt;" &lt;?php echo $rows['attr_type_id']==$attr_type_id?'selected':''?&gt;&gt;&lt;?php echo $rows['attr_type_name']?&gt;&lt;/option&gt;</div><div class="line">    &lt;?php endforeach;?&gt;</div><div class="line">   &lt;/select&gt;</div><div class="line">  &lt;/form&gt;</div><div class="line">&lt;/div&gt;</div></pre></td></tr></table></figure></p>
<h1 id="切换选项禁用状态"><a href="#切换选项禁用状态" class="headerlink" title="切换选项禁用状态"></a>切换选项禁用状态</h1><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line">&lt;form action="" method="post" name="theForm" &gt;</div><div class="line">&lt;table width="100%" id="general-table"&gt;</div><div class="line">  &lt;tr&gt;</div><div class="line">    &lt;td class="label"&gt;该属性值的录入方式：&lt;/td&gt;</div><div class="line">	&lt;td&gt;</div><div class="line">      &lt;input type="radio" name="attr_input_type" value="0" checked="true" onclick="radioClicked(0)"&gt;</div><div class="line">      手工录入</div><div class="line">      &lt;input type="radio" name="attr_input_type" value="1" onclick="radioClicked(1)" &lt;?php echo $info['attr_input_type']==1?'checked':''?&gt;&gt;从下面的列表中选择（一行代表一个可选值）</div><div class="line">      &lt;input type="radio" name="attr_input_type" value="2" onclick="radioClicked(0)" &lt;?php echo $info['attr_input_type']==2?'checked':''?&gt;&gt;多行文本框</div><div class="line">    &lt;/td&gt;</div><div class="line">  &lt;/tr&gt;</div><div class="line">&lt;/table&gt;</div><div class="line">&lt;/form&gt;</div><div class="line">&lt;script type="text/javascript"&gt;</div><div class="line">/**</div><div class="line"> * 点击类型按钮时切换选项的禁用状态</div><div class="line"> */</div><div class="line">function radioClicked(n)</div><div class="line">&#123;</div><div class="line">  document.forms['theForm'].elements["attr_input_value"].disabled = n &gt; 0 ? false : true;</div><div class="line">&#125;</div><div class="line">&lt;/script&gt;</div></pre></td></tr></table></figure>
          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20161008-2.html" itemprop="url">
                  PHP - 错误处理 | 异常处理
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-08T23:47:19+08:00" content="2016-10-08">
              2016-10-08
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20161008-2.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20161008-2.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="错误处理简介"><a href="#错误处理简介" class="headerlink" title="错误处理简介"></a>错误处理简介</h1><p><strong>PHP独有的处理</strong><br>默认情况下，当错误发生的时候在浏览器上显示错误报告。<br>可以使用操作符（@）来屏蔽语句生成的错误报告，注意@符号只对函数有用，对echo语句不起作用</p>
<h3 id="错误级别"><a href="#错误级别" class="headerlink" title="错误级别"></a>错误级别</h3><p>按照错误的严重程度将错误划分为3种<br>Notice：提示性错误<br>Warning：警告性错误<br>Fatal error：致命性错误</p>
<blockquote>
<p>notice和warning级别错误后继续执行，error级别错误后终止执行</p>
</blockquote>
<h3 id="处理方式"><a href="#处理方式" class="headerlink" title="处理方式"></a>处理方式</h3><p>显示错误报告【默认】<br>记录错误日志<br>错误发生后交个自定义脚本去完成【比如，错误发生后发一个电子邮件】</p>
<h3 id="错误触发"><a href="#错误触发" class="headerlink" title="错误触发"></a>错误触发</h3><p>PHP程序触发：PHP在运行的过程中，发现并触发错误。比如include、require等等。<br>由用户触发，通过trigger_error()来触发错误。<br>eg:定义年龄不能超过30，超过30即报错<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">$age = 30;</div><div class="line">if($age&gt;30)</div><div class="line">	trigger_error(&quot;age cannot over 30&quot;,E_USER_ERROR);</div></pre></td></tr></table></figure></p>
<p>用户错误的级别，他们是常量,默认触发notice错误。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">;E_USER_ERROR	- user-generated error message</div><div class="line">;E_USER_WARNING - user-generated warning message</div><div class="line">;E_USER_NOTICE  - user-generated notice message</div></pre></td></tr></table></figure></p>
<h3 id="实现错误处理"><a href="#实现错误处理" class="headerlink" title="实现错误处理"></a>实现错误处理</h3><h4 id="更改php配置有3种方法"><a href="#更改php配置有3种方法" class="headerlink" title="更改php配置有3种方法"></a>更改php配置有3种方法</h4><h5 id="在php-ini中更改"><a href="#在php-ini中更改" class="headerlink" title="在php.ini中更改"></a>在php.ini中更改</h5><p>所有的虚拟目录中有效</p>
<h5 id="htaccess分布式部署文件"><a href="#htaccess分布式部署文件" class="headerlink" title=".htaccess分布式部署文件"></a>.htaccess分布式部署文件</h5><p>.htaccess通过php_flag和php_value 在某个虚拟目录，或某个目录有效.</p>
<h5 id="ini-set-：某一个页面有效"><a href="#ini-set-：某一个页面有效" class="headerlink" title="ini_set()：某一个页面有效"></a>ini_set()：某一个页面有效</h5><p><code>ini_set(&#39;display_errors&#39;:&#39;on&#39;)</code> 开启错误显示<br><code>ini_set(&#39;display_errors&#39;:&#39;off&#39;)</code> 关闭错误显示</p>
<h4 id="在浏览器上显示错误报告"><a href="#在浏览器上显示错误报告" class="headerlink" title="在浏览器上显示错误报告"></a>在浏览器上显示错误报告</h4><p><code>display_errors = On</code></p>
<h4 id="在日志中显示错误报告"><a href="#在日志中显示错误报告" class="headerlink" title="在日志中显示错误报告"></a>在日志中显示错误报告</h4><p><code>log_errors = On</code><br>错误日志保存的地址<br><code>error_log = php_errors.log</code></p>
<h4 id="用户自定义错误处理"><a href="#用户自定义错误处理" class="headerlink" title="用户自定义错误处理"></a>用户自定义错误处理</h4><p>默认情况下，一旦定义了错误处理函数，则错误报告和错误日志不再执行</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">error</span><span class="params">()</span></span>&#123;</div><div class="line">	<span class="keyword">echo</span> <span class="string">'这是自定义错误'</span>;</div><div class="line">&#125;</div><div class="line"><span class="comment">//注册错误处理函数</span></div><div class="line">set_error_handler(<span class="string">'error'</span>);</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<blockquote>
<p>在自定义错误处理函数中添加return false，则自定义错误处理后再交个PHP处理。</p>
</blockquote>
<p>应用：不同的级别使用不同错误处理<br><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="comment">/**</span></div><div class="line">*<span class="doctag">@param</span> $level 错误级别</div><div class="line">*<span class="doctag">@param</span> $msg	错误信息</div><div class="line">*<span class="doctag">@param</span> $file	错误文件</div><div class="line">*<span class="doctag">@param</span> $line	错误行号</div><div class="line">*/</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">error</span><span class="params">($level,$msg,$file,$line)</span> </span>&#123;</div><div class="line">	<span class="keyword">switch</span>($level) &#123;</div><div class="line">		<span class="keyword">case</span> E_NOTICE:</div><div class="line">		<span class="keyword">case</span> E_USER_NOTICE:</div><div class="line">			<span class="keyword">echo</span> <span class="string">'将错误信息屏蔽掉&lt;br&gt;'</span>;</div><div class="line">			<span class="keyword">break</span>;</div><div class="line">		<span class="keyword">case</span> E_WARNING :</div><div class="line">		<span class="keyword">case</span> E_USER_WARNING:</div><div class="line">			<span class="keyword">echo</span> <span class="string">'将错误信息记录到日志中&lt;br&gt;'</span>;</div><div class="line">			<span class="keyword">break</span>;</div><div class="line">		<span class="keyword">case</span> E_ERROR:</div><div class="line">		<span class="keyword">case</span> E_USER_ERROR:</div><div class="line">			<span class="keyword">echo</span> <span class="string">'给管理员发邮件&lt;br&gt;'</span>;</div><div class="line">			<span class="keyword">break</span>;</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">echo</span> <span class="string">"错误信息：&#123;$msg&#125;&lt;br&gt;"</span>;</div><div class="line">	<span class="keyword">echo</span> <span class="string">"错误文件：&#123;$file&#125;&lt;br&gt;"</span>;</div><div class="line">	<span class="keyword">echo</span> <span class="string">"错误行号：&#123;$line&#125;"</span>;</div><div class="line">&#125;</div><div class="line">set_error_handler(<span class="string">'error'</span>);	<span class="comment">//注册错误处理函数</span></div><div class="line">header(<span class="string">'content-type:text/html;charset=utf-8'</span>);</div><div class="line"><span class="keyword">echo</span> $aa,<span class="string">'&lt;hr&gt;'</span>;</div><div class="line"><span class="keyword">include</span> <span class="string">'./aa.php'</span>;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure></p>
<h3 id="指定显示错误级别"><a href="#指定显示错误级别" class="headerlink" title="指定显示错误级别"></a>指定显示错误级别</h3><p><code>;Error Level Constants:</code><br><code>error_reporting = E_ALL | E_STRICT</code><br>思考：为什么在php5.3中显示所有错误是E_ALL | E_STRICT？<br>答：在php5.3中，E_ALL不是表示所有错误，E_ALL | E_STRICT也表示所有错误。<br>在php5.4以上版本，E_ALL的错误都会报的。</p>
<p>E_ALL:   111011111111111<br>E_STRICT:000100000000000</p>
<p>例题：<br>只有PHP的notice才报错<br><code>ini_set(&#39;error_reporting&#39;,E_NOTICE);</code><br>只报PHP的notice和用户的notice<br><code>ini_set(&#39;error_reporting&#39;,E_NOTICE | E_USER_NOTICE);</code><br>系统的notice不报，其他全报<br><code>ini_set(&#39;error_reporting&#39;,(E_ALL | E_STRICT) &amp; ~E_NOTICE);</code></p>
<blockquote>
<p>~是按位取非，0变成1,1变成0。</p>
</blockquote>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span> </div><div class="line"><span class="comment">/**</span></div><div class="line"> * 自定义错误处理函数</div><div class="line"> * <span class="doctag">@param</span>  int $level 错误级别</div><div class="line"> * <span class="doctag">@param</span>  string $msg   错误信息</div><div class="line"> * <span class="doctag">@param</span>  string $file  错误文件名</div><div class="line"> * <span class="doctag">@param</span>  int $line  错误行号</div><div class="line"> * <span class="doctag">@return</span> Bool        错误处理情况</div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">error</span><span class="params">($level,$msg,$file,$line)</span></span>&#123;</div><div class="line">	<span class="keyword">switch</span> ($level) &#123;</div><div class="line">		<span class="keyword">case</span> E_NOTICE:</div><div class="line">		<span class="keyword">case</span> E_USER_NOTICE:</div><div class="line">			<span class="keyword">echo</span> <span class="string">'将错误屏蔽'</span>;</div><div class="line">			<span class="keyword">break</span>;</div><div class="line">		<span class="keyword">case</span> E_WARNING:</div><div class="line">		<span class="keyword">case</span> E_USER_WARNING:</div><div class="line">			<span class="keyword">echo</span> <span class="string">'将错误记录在日志中&lt;br&gt;'</span>;</div><div class="line">			<span class="keyword">break</span>;</div><div class="line">		<span class="comment">// case E_ERROR: //一般不设置，若报了该错误，程序将终止运行</span></div><div class="line">		<span class="keyword">case</span> E_USER_ERROR:</div><div class="line">			<span class="keyword">echo</span> <span class="string">'将错误发送给管理员&lt;br&gt;'</span>;</div><div class="line">			<span class="keyword">break</span>;</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">echo</span> <span class="string">'错误信息：'</span>.$msg,<span class="string">"&lt;br&gt;"</span>;</div><div class="line">	<span class="keyword">echo</span> <span class="string">'错误文件：'</span>.$file.<span class="string">"&lt;br&gt;"</span>;</div><div class="line">	<span class="keyword">echo</span> <span class="string">'错误行号：'</span>.$line,<span class="string">'&lt;br&gt;'</span>;</div><div class="line">	<span class="comment">// return false 自定义错误处理完毕后，交给计算机继续处理</span></div><div class="line">	<span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">&#125;</div><div class="line"><span class="comment">// 注册错误函数</span></div><div class="line">set_error_handler(<span class="string">'error'</span>);</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h1 id="项目中的错误处理"><a href="#项目中的错误处理" class="headerlink" title="项目中的错误处理"></a>项目中的错误处理</h1><p>项目开发的时候错误显示在浏览器上，不用记录在日志中<br>项目运行的时候错误记录在日志中，不显示在浏览器上</p>
<ul>
<li>php.ini  log_errors = on 开启错误日志</li>
<li>php.ini  error_log = $log_path.$error_log;</li>
</ul>
<p>将项目的运行模式分为“开发模式（调试模式）”和“运行模式”</p>
<ul>
<li>在配置文件中，添加一个配置用来保存开发的模式</li>
<li>在Application文件夹下新建Log文件夹，用来保存日志</li>
<li>在Framework类中添加定义Log文件夹的路径常量</li>
<li>在Framework类中定义错误处理的方法<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span> </div><div class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">initError</span><span class="params">()</span></span>&#123;</div><div class="line">	ini_set(<span class="string">'error_reporting'</span>, E_ALL | E_STRICT); <span class="comment">//报所有错误</span></div><div class="line">	<span class="keyword">if</span>($GLOBALS[<span class="string">'config'</span>][<span class="string">'app'</span>][<span class="string">'app_dubeg'</span>])&#123;<span class="comment">//开发模式</span></div><div class="line">		ini_set(<span class="string">'display_errors'</span>,<span class="string">'on'</span>); <span class="comment">//浏览器显示错误</span></div><div class="line">		ini_set(<span class="string">'log_errors'</span>,<span class="string">'off'</span>); <span class="comment">//不记录日志</span></div><div class="line">	&#125;<span class="keyword">else</span>&#123;</div><div class="line">		ini_set(<span class="string">'display_errors'</span>,<span class="string">'off'</span>); <span class="comment">//浏览器不显示错误</span></div><div class="line">		ini_set(<span class="string">'log_errors'</span>,<span class="string">'on'</span>); <span class="comment">//记录日志</span></div><div class="line">		$error_log = date(<span class="string">'Y-m-d'</span>).<span class="string">'.log'</span>;</div><div class="line">		ini_set(<span class="string">'error_log'</span>,LOG_PATH.$error_log);</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"> <span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h1><p>异常处理使用关键字：try、catch、throw</p>
<ol>
<li>try:用来监测代码</li>
<li>thr ow：用来抛出异常</li>
<li>catch：用来捕获异常</li>
<li>Exception：PHP内置的异常类,是所有异常类的父类</li>
</ol>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line">&lt;!DOCTYPE html&gt;</div><div class="line">&lt;html lang=<span class="string">"en"</span>&gt;</div><div class="line">&lt;head&gt;</div><div class="line">	&lt;meta charset=<span class="string">"UTF-8"</span>&gt;</div><div class="line">	&lt;title&gt;Document&lt;/title&gt;</div><div class="line">&lt;/head&gt;</div><div class="line">&lt;body&gt;</div><div class="line">	<span class="meta">&lt;?php</span> </div><div class="line">		<span class="keyword">if</span>(<span class="keyword">isset</span>($_POST[<span class="string">'button'</span>]))&#123;</div><div class="line">			<span class="keyword">try</span>&#123;</div><div class="line">				$age = $_POST[<span class="string">'age'</span>];</div><div class="line">				<span class="keyword">if</span> ($age&lt;<span class="number">20</span> || $age&gt;<span class="number">30</span>) &#123;</div><div class="line">					<span class="keyword">throw</span> <span class="keyword">new</span> <span class="keyword">Exception</span>(<span class="string">'年龄必须在20到30之间'</span>);<span class="comment">//抛出异常类</span></div><div class="line">					<span class="keyword">echo</span> <span class="string">'错误抛出后这里不会再执行了'</span>;</div><div class="line">				&#125;<span class="keyword">else</span>&#123;</div><div class="line">					<span class="keyword">echo</span> <span class="string">'青春年少，用行动做一辈子不能被注定的事！'</span>;</div><div class="line">				&#125;</div><div class="line">			&#125;<span class="keyword">catch</span>(<span class="keyword">Exception</span> $e)&#123;  <span class="comment">//数据类型约束，只能是Exception</span></div><div class="line">				<span class="comment">//catch 用来捕获错误</span></div><div class="line">				<span class="keyword">echo</span> <span class="string">'错误信息：'</span>.$e-&gt;getMessage().<span class="string">'&lt;br&gt;'</span>;</div><div class="line">				<span class="keyword">echo</span> <span class="string">'异常码：'</span>.$e-&gt;getCode().<span class="string">'&lt;br&gt;'</span>;</div><div class="line">				<span class="keyword">echo</span> <span class="string">'当前文件：'</span>.$e-&gt;getFile().<span class="string">'&lt;br&gt;'</span>;</div><div class="line">				<span class="keyword">echo</span> <span class="string">'异常行号：'</span>.$e-&gt;getLine().<span class="string">'&lt;br&gt;'</span>;</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">	 <span class="meta">?&gt;</span></div><div class="line">	 &lt;form action=<span class="string">""</span> method=<span class="string">"post"</span>&gt;</div><div class="line">	 	请输入年龄：&lt;input type=<span class="string">"text"</span> name=<span class="string">"age"</span>&gt;&lt;br&gt;</div><div class="line">	 	&lt;input type=<span class="string">"submit"</span> name=<span class="string">"button"</span> value=<span class="string">"提交"</span>&gt;</div><div class="line">	 &lt;/form&gt;</div><div class="line">&lt;/body&gt;</div><div class="line">&lt;/html&gt;</div></pre></td></tr></table></figure>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20161008-1.html" itemprop="url">
                  PHP - 文件上传 | 缩略图
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-08T23:46:01+08:00" content="2016-10-08">
              2016-10-08
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20161008-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20161008-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="文件上传"><a href="#文件上传" class="headerlink" title="文件上传"></a>文件上传</h1><hr>
<h3 id="表单的enctype属性："><a href="#表单的enctype属性：" class="headerlink" title="表单的enctype属性："></a>表单的enctype属性：</h3><ul>
<li><code>application/x-www-fomr-urlencoded</code> ：表示表单先服务器传输的文件数据。这是默认格式。(将表单的数据转成XML格式向服务器传输)</li>
<li><code>multipart/form-data</code> ：符合数据，告知浏览器表单中是符合数据（字符串，二进制文件）</li>
<li><code>text/plain</code>：用于向服务器传输大量文本，效率高，但时安全性低，用于发送邮件<br>表示表单传输的数据类型</li>
</ul>
<p><strong>表单文件域</strong></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">method</span>=<span class="string">"post"</span> <span class="attr">action</span>=<span class="string">""</span> <span class="attr">enctype</span>=<span class="string">"multipart/form-data"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"file"</span> <span class="attr">name</span>=<span class="string">""</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"submit"</span> <span class="attr">name</span>=<span class="string">"button"</span> <span class="attr">value</span>=<span class="string">"上传"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<h3 id="超全局变量"><a href="#超全局变量" class="headerlink" title="超全局变量"></a><strong>超全局变量</strong></h3><p><code>$_FILES</code><br><code>$_FILES[][&#39;name&#39;]</code> ：上传文件名<br><code>$_FILES[][&#39;size&#39;]</code>    ：文件上传的大小</p>
<p><strong><code>$_FILES[][&#39;error&#39;]</code>    ：文件上传的错误号 0，1，2，3，4，6，7</strong></p>
<blockquote>
<p>UPLOAD_ERR_OK：值为 0，没有错误发生，文件上传成功。<br><code>UPLOAD_ERR_INI_SIZE</code> ： 值为 1，上传的文件超过了 php.ini 中 <code>upload_max_filesize</code> 选项限制的值。<br><code>UPLOAD_ERR_FORM_SIZE</code>：值为 2，上传文件的大小超过了 HTML 表单中 <code>MAX_FILE_SIZE</code> 选项指定的值。<code>&lt;input type=&#39;hidden&#39; name=&#39;MAX_FILE_SIZE&#39; value=&#39;2&#39;&gt;</code>,隐藏域必须在文件域前面才起作用。<br><code>UPLOAD_ERR_PARTIAL</code>：值为 3，文件只有部分被上传。<br><code>UPLOAD_ERR_NO_FILE</code>：值为 4，没有文件被上传。<br><code>UPLOAD_ERR_NO_TMP_DIR</code>：值为 6，找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。<br><code>UPLOAD_ERR_CANT_WRITE</code>：值为 7，文件写入失败。PHP 5.1.0 引进。</p>
</blockquote>
<p>补充：</p>
<blockquote>
<p>表单允许POST传输的最大值：<br><code>post_max_size = 8M</code></p>
</blockquote>
<p><strong><code>$_FILES[][&#39;type&#39;]</code>    ：上传文件格式，返回MIMIE格式 语法：类型/格式</strong><br><strong><code>$_FILES[][&#39;tmp&#39;]</code>    ：文件上传的临时目录</strong> </p>
<blockquote>
<p><code>upload_tmp_dir=&#39;F:\wamp\tmp&#39;</code>  临时目录地址</p>
</blockquote>
<p>php.ini 配置文件<br><code>file_uploads = On</code> 是否允许文件上传<br><code>max_file_uploads = 20</code> 同时最多允许上传20个文件</p>
<h3 id="move-uploaded-file-移动上传文件"><a href="#move-uploaded-file-移动上传文件" class="headerlink" title="move_uploaded_file()移动上传文件"></a><strong>move_uploaded_file()移动上传文件</strong></h3><p><code>bool move_uploaded_file ( string $filename , string $destination )</code><br><code>$filename</code>：上传的文件的文件名。<br><code>$destination</code>：移动文件到这个位置。</p>
<p><strong>常用函数</strong><br><code>bool is_uploaded_file ( string $filename )</code> — 判断文件是否是通过 HTTP POST 上传的<br><code>is_uploaded_file($_FILES[&#39;userfile&#39;][&#39;tmp_name&#39;])</code>：用来确保恶意的用户无法欺骗脚本去访问本不能访问的文件，例如 /etc/passwd</p>
<p><strong>文件名截取</strong><br>方法一：<code>strrchr($filename,&#39;.&#39;);</code> 从最后出现的点截取到末尾<br>方法二：pathinfo($filename); 通过文件路径返回文件信息</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$path_parts = pathinfo(<span class="string">'/www/htdocs/inc/lib.inc.php'</span>);</div><div class="line"></div><div class="line"><span class="keyword">echo</span> $path_parts[<span class="string">'dirname'</span>], <span class="string">"\n"</span>;</div><div class="line"><span class="keyword">echo</span> $path_parts[<span class="string">'basename'</span>], <span class="string">"\n"</span>;</div><div class="line"><span class="keyword">echo</span> $path_parts[<span class="string">'extension'</span>], <span class="string">"\n"</span>;</div><div class="line"><span class="keyword">echo</span> $path_parts[<span class="string">'filename'</span>], <span class="string">"\n"</span>; <span class="comment">// since PHP 5.2.0</span></div><div class="line"><span class="meta">?&gt;</span></div><div class="line">/www/htdocs/inc</div><div class="line">lib.inc.php</div><div class="line">php</div><div class="line">lib.inc</div></pre></td></tr></table></figure>
<blockquote>
<p>以上两种方法方法可以被伪装（强制修改文件扩展名）</p>
</blockquote>
<p>方法三：开启<code>fileinfo</code>扩展<code>extension_fileinfo.dll</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">$finfo = finfo_open(FILEINFO_MIME); //创建finfo对象，用来匹配文件</div><div class="line">$info = finfo_file($finfo,&apos;F:/image.jpg&apos;);//通过对象匹配文件</div><div class="line">var_dump($info);//显示文件信息</div></pre></td></tr></table></figure>
<p>文件上传注意事项：</p>
<blockquote>
<p>上传文件的大小限制（文件上传<code>upload_max_filesize</code>、post大小<code>post_max_size</code>、表单隐藏域<code>&lt;input type=&#39;hidden&#39; name=&#39;MAX_FILE_SIZE&#39; value=&#39;2&#39;&gt;</code>,文件域之前）<br>文件格式验证的三种方法：<br>路径截取、pathinfo、fileinfo</p>
</blockquote>
<h3 id="生成唯一文件名"><a href="#生成唯一文件名" class="headerlink" title="生成唯一文件名"></a>生成唯一文件名</h3><p>time().rand(100,999).strrchr($path,’.’);</p>
<p>uniqid().strrchar($path,’.’);</p>
<blockquote>
<p><code>string uniqid ([ string $prefix = &quot;&quot; [, bool $more_entropy = false ]] )</code>,可选前缀<code>prefix</code>、基于当前时间微秒数的唯一ID。设置第二个参数<code>more_entropy</code>为<code>TRUE</code>，返回唯一ID更具唯一性。</p>
</blockquote>
<h3 id="优化文件上传"><a href="#优化文件上传" class="headerlink" title="优化文件上传"></a>优化文件上传</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="comment">/*</span></div><div class="line">** +-------------------------------------------</div><div class="line">** | Author: uiste [ JUST DO IT ]</div><div class="line">** +-------------------------------------------</div><div class="line">** | Date: 2016/10/8 Time: 19:50 </div><div class="line">** +-------------------------------------------</div><div class="line">** | Connection: &lt;blog.uiste.com&gt;</div><div class="line">** +-------------------------------------------</div><div class="line">*/</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * Class UploadLib 文件上传类</div><div class="line"> */</div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">UploadLib</span></span>&#123;</div><div class="line">    <span class="comment">//保存操作获取的错误信息</span></div><div class="line">    <span class="keyword">private</span> $error;</div><div class="line">    <span class="comment">//外部调用文件上传的错误信息</span></div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getError</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;error;</div><div class="line">    &#125;</div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 文件上传优化类</div><div class="line">     * <span class="doctag">@param</span>  array $file 文件上传获取的数组信息</div><div class="line">     * <span class="doctag">@return</span> string       上传文件的路径</div><div class="line">     */</div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">upload</span><span class="params">($file)</span></span>&#123;</div><div class="line">        <span class="comment">/**</span></div><div class="line">         * 验证错误信息，保存到私有属性中</div><div class="line">         */</div><div class="line">        <span class="keyword">if</span> ($file[<span class="string">'error'</span>]!==<span class="number">0</span>) &#123;</div><div class="line">            <span class="keyword">switch</span> ($file[<span class="string">'error'</span>]) &#123;</div><div class="line">                <span class="keyword">case</span> <span class="number">1</span>:</div><div class="line">                    <span class="keyword">$this</span>-&gt;error = <span class="string">"上传文件超过了配置文件中允许的最大值"</span>;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                <span class="keyword">case</span> <span class="number">2</span>:</div><div class="line">                    <span class="keyword">$this</span>-&gt;error = <span class="string">"上传文件超过了表单允许的最大值"</span>;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                <span class="keyword">case</span> <span class="number">3</span>:</div><div class="line">                    <span class="keyword">$this</span>-&gt;error = <span class="string">"只有部分文件上传，没有完全上传"</span>;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                <span class="keyword">case</span> <span class="number">4</span>:</div><div class="line">                    <span class="keyword">$this</span>-&gt;error = <span class="string">"没有文件被上传"</span>;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                <span class="keyword">case</span> <span class="number">6</span>:</div><div class="line">                    <span class="keyword">$this</span>-&gt;error = <span class="string">"找不到临时文件"</span>;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                <span class="keyword">case</span> <span class="number">7</span>:</div><div class="line">                    <span class="keyword">$this</span>-&gt;error = <span class="string">"文件写入失败"</span>;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                <span class="keyword">default</span>:</div><div class="line">                    <span class="keyword">$this</span>-&gt;error = <span class="string">"其它未知错误"</span>;</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">            &#125;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="comment">/**</span></div><div class="line">         * 验证文件类型</div><div class="line">         * <span class="doctag">@param</span> array $allow_types 允许上传的文件类型</div><div class="line">         * <span class="doctag">@param</span> resource $finfo MIME资源，用于finfo_file匹配需求</div><div class="line">         * <span class="doctag">@param</span> string $info 文件类型与编码信息的字符串</div><div class="line">         * <span class="doctag">@param</span> array $type_mime 截取mime文件类型</div><div class="line">         */</div><div class="line">        $allow_types = <span class="keyword">array</span>(<span class="string">"image/jpeg"</span>,<span class="string">"image/png"</span>,<span class="string">"image/gif"</span>);</div><div class="line">        $finfo = finfo_open(FILEINFO_MIME);</div><div class="line">        $info = finfo_file($finfo, $file[<span class="string">'tmp_name'</span>]);</div><div class="line">        $info_array = explode(<span class="string">';'</span>,$info);</div><div class="line">        $type_mime = $info_array[<span class="number">0</span>];</div><div class="line">        <span class="keyword">if</span> (!in_array($type_mime,$allow_types)) &#123;</div><div class="line">            <span class="keyword">$this</span>-&gt;error = <span class="string">"文件类型错误，不能上传"</span>.$type_mime.<span class="string">"类型的文件"</span>;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="comment">/**</span></div><div class="line">         * 验证文件类型</div><div class="line">         * <span class="doctag">@param</span> byte $file['size'] 上传文件的大小</div><div class="line">         * <span class="doctag">@param</span> byte $GLOBALS['config']['file']['allow_size'] 网站允许上传的文件大小</div><div class="line">         */</div><div class="line">        <span class="keyword">if</span> ($file[<span class="string">'size'</span>]&gt;$GLOBALS[<span class="string">'config'</span>][<span class="string">'file'</span>][<span class="string">'allow_size'</span>]) &#123;</div><div class="line">            <span class="keyword">$this</span>-&gt;error = <span class="string">"上传文件大小是:"</span>.number_format($file[<span class="string">'size'</span>]/<span class="number">1024</span>/<span class="number">1024</span>,<span class="number">2</span>).<span class="string">"M;超过了网站允许的最大值:"</span>.number_format($GLOBALS[<span class="string">'config'</span>][<span class="string">'file'</span>][<span class="string">'allow_size'</span>]/<span class="number">1024</span>/<span class="number">1024</span>,<span class="number">2</span>).<span class="string">"M"</span>;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="comment">/**</span></div><div class="line">         * 验证文件是否通过HTTP POST上传</div><div class="line">         */</div><div class="line">        <span class="keyword">if</span> (!is_uploaded_file($file[<span class="string">'tmp_name'</span>])) &#123;</div><div class="line">            <span class="keyword">$this</span>-&gt;error = <span class="string">"非法上传文件，必须通过HTTP上传"</span>;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="comment">/**</span></div><div class="line">         * 创建上传文件夹</div><div class="line">         * <span class="doctag">@param</span> array $type 拆分MIME类型文件类型与文件格式</div><div class="line">         * <span class="doctag">@param</span> string $folder_set 定义级联文件夹</div><div class="line">         * <span class="doctag">@param</span> string $folder_path 网站配置上传文件路径与级联路径后的全路径</div><div class="line">         * <span class="doctag">@param</span> string $file_name 上传文件重新生成的唯一文件名</div><div class="line">         * <span class="doctag">@param</span> string $file_path 文件全路径，包含文件名</div><div class="line">         */</div><div class="line">        $type = explode(<span class="string">'/'</span>, $type_mime);<span class="comment">//获取的文件类型与文件格式两个值</span></div><div class="line">        $folder_set = $type[<span class="number">0</span>].DS.$type[<span class="number">1</span>].DS.date(<span class="string">'Ym'</span>).DS;</div><div class="line">        $folder_path = $GLOBALS[<span class="string">'config'</span>][<span class="string">'file'</span>][<span class="string">'upload_path'</span>].DS.$folder_set;</div><div class="line">        $file_name = uniqid(<span class="string">''</span>,<span class="keyword">true</span>).<span class="string">'.'</span>.$type[<span class="number">1</span>];</div><div class="line">        $file_path = $folder_path.$file_name;</div><div class="line">        <span class="keyword">if</span> (!file_exists($folder_path)) &#123;</div><div class="line">            <span class="keyword">if</span> (!mkdir($folder_path,<span class="number">0777</span>,<span class="keyword">true</span>)) &#123;</div><div class="line">                <span class="keyword">$this</span>-&gt;error = <span class="string">"上传文件夹创建失败"</span>;</div><div class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">            &#125;</div><div class="line"></div><div class="line">        &#125;</div><div class="line">        <span class="comment">//上传文件</span></div><div class="line">        <span class="keyword">if</span> (move_uploaded_file($file[<span class="string">'tmp_name'</span>], $file_path)) &#123;</div><div class="line">            <span class="keyword">return</span> $folder_set.$file_name;</div><div class="line">        &#125;<span class="keyword">else</span>&#123;</div><div class="line">            <span class="keyword">$this</span>-&gt;error = <span class="string">"文件上传失败"</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h3 id="多文件上传"><a href="#多文件上传" class="headerlink" title="多文件上传"></a>多文件上传</h3><p>表单命名以数组的形式，接收到的数据，按相同的<strong>属性</strong>组成一个索引数组</p>
<h1 id="缩略图"><a href="#缩略图" class="headerlink" title="缩略图"></a>缩略图</h1><hr>
<p><code>bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )</code><br>重采样拷贝部分图像并调整大小</p>
<blockquote>
<p>dst_image：目标图象连接资源。<br>src_image：源图象连接资源。<br>dst_x：目标 X 坐标点。<br>dst_y：目标 Y 坐标点。<br>src_x：源的 X 坐标点。<br>src_y：源的 Y 坐标点。<br>dst_w：目标宽度。<br>dst_h：目标高度。<br>src_w：源图象的宽度。<br>src_h：源图象的高度</p>
</blockquote>
<h1 id="等比缩略图"><a href="#等比缩略图" class="headerlink" title="等比缩略图"></a>等比缩略图</h1><hr>
<p>思想：按图的长宽比例进行比较，源图的比例大的为标准，短边进行等比压缩。</p>
<blockquote>
<p>压缩目标图边的长度=源图缩放边的长度*目标图标准边长度/源图标准边的长度</p>
</blockquote>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="comment">/*</span></div><div class="line">** +-------------------------------------------</div><div class="line">** | Author: uiste [ JUST DO IT ]</div><div class="line">** +-------------------------------------------</div><div class="line">** | Date: 2016/10/8 Time: 19:50 </div><div class="line">** +-------------------------------------------</div><div class="line">** | Connection: &lt;blog.uiste.com&gt;</div><div class="line">** +-------------------------------------------</div><div class="line">*/</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * Class ThumbLib 生成缩略图</div><div class="line"> */</div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">ThumbLib</span></span>&#123;</div><div class="line">    <span class="comment">//保存操作获取的错误信息</span></div><div class="line">    <span class="keyword">private</span> $error;</div><div class="line">    <span class="comment">//外部调用文件上传的错误信息</span></div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getError</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;error;</div><div class="line">    &#125;</div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 生成缩略图</div><div class="line">     * <span class="doctag">@param</span> string $src_path 源图路径资源</div><div class="line">     * <span class="doctag">@param</span> int $max_w 缩略图的最大宽度，若调用时不传递就直接使用配置文件的大小</div><div class="line">     * <span class="doctag">@param</span> int $max_h 缩略图的最大高度，同上</div><div class="line">     * <span class="doctag">@param</span> bool $is_ration 是否等比缩放</div><div class="line">     * <span class="doctag">@param</span> string $prefix 缩略图文件名前缀</div><div class="line">     * <span class="doctag">@return</span> string 返回缩略图路径</div><div class="line">     */</div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">thumb</span><span class="params">($src_path,$max_w=<span class="string">''</span>,$max_h=<span class="string">''</span>,$is_ratio=true,$prefix=<span class="string">'small_'</span>)</span></span>&#123;</div><div class="line">        $max_w = $max_w!=<span class="string">''</span> ? $max_w : $GLOBALS[<span class="string">'config'</span>][<span class="string">'file'</span>][<span class="string">'thumb_w'</span>] ;</div><div class="line">        $max_h = $max_h!=<span class="string">''</span>	? $max_h : $GLOBALS[<span class="string">'config'</span>][<span class="string">'file'</span>][<span class="string">'thumb_h'</span>] ;</div><div class="line">        $ext = strtolower(strrchr($src_path,<span class="string">'.'</span>));<span class="comment">//获取文件的后缀</span></div><div class="line">        $type = <span class="string">''</span>;</div><div class="line">        <span class="keyword">switch</span> ($ext) &#123;</div><div class="line">            <span class="keyword">case</span> <span class="string">'.jpg'</span>:</div><div class="line">                $type = <span class="string">'jpeg'</span>;</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            <span class="keyword">case</span> <span class="string">'.jpeg'</span>:</div><div class="line">                $type = <span class="string">'jpeg'</span>;</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            <span class="keyword">case</span> <span class="string">'.png'</span>:</div><div class="line">                $type = <span class="string">'png'</span>;</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            <span class="keyword">case</span> <span class="string">'.gif'</span>:</div><div class="line">                $type = <span class="string">'gif'</span>;</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            <span class="keyword">default</span>:</div><div class="line">                <span class="keyword">$this</span>-&gt;error = <span class="string">"不支持该文件类型"</span>.$ext;</div><div class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">        &#125;</div><div class="line">        $open_fn = <span class="string">'imagecreatefrom'</span>.$type; <span class="comment">//拼接函数名</span></div><div class="line">        <span class="comment">// 创建缩略图画布</span></div><div class="line">        $dst_img = imagecreatetruecolor($max_w, $max_h);</div><div class="line">        <span class="comment">// 打开源图片资源</span></div><div class="line">        $src_path_all = $GLOBALS[<span class="string">'config'</span>][<span class="string">'file'</span>][<span class="string">'upload_path'</span>].DS.$src_path;</div><div class="line">        <span class="keyword">if</span>(!$src_img = $open_fn($src_path_all))&#123;</div><div class="line">           <span class="keyword">$this</span>-&gt;error = <span class="string">"源图路径错误或者不全"</span>;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">        &#125;</div><div class="line">        $src_w = imagesx($src_img);</div><div class="line">        $src_h = imagesy($src_img);</div><div class="line">        <span class="keyword">if</span> ($is_ratio) &#123;</div><div class="line">            <span class="keyword">if</span> ($src_w/$src_h&gt;$max_w/$max_h) &#123;</div><div class="line">                <span class="comment">#若源图的宽度较长，则等比缩放高度</span></div><div class="line">                $dst_w = $max_w;</div><div class="line">                $dst_h = $dst_w*$src_h/$src_w;</div><div class="line">            &#125;<span class="keyword">else</span>&#123;</div><div class="line">                <span class="comment">#如源图的高度较长，则等比缩放宽度</span></div><div class="line">                $dst_h = $max_h;</div><div class="line">                $dst_w = $dst_h*$src_w/$src_h;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// 求目标图的坐标</span></div><div class="line">        $dst_x = (int)(($max_w-$dst_w)/<span class="number">2</span>);</div><div class="line">        $dst_y = (int)(($max_h-$dst_h)/<span class="number">2</span>);</div><div class="line">        <span class="comment">// 生成缩略图</span></div><div class="line">        imagecopyresampled($dst_img, $src_img, $dst_x, $dst_y, <span class="number">0</span>, <span class="number">0</span>, $dst_w, $dst_h, $src_w, $src_h);</div><div class="line">        <span class="comment">// 保存缩略图</span></div><div class="line">        $folderpath = dirname($src_path);<span class="comment">//获取目录地址</span></div><div class="line">        $filename = basename($src_path); <span class="comment">//获取文件名</span></div><div class="line">        $small_path = $GLOBALS[<span class="string">'config'</span>][<span class="string">'file'</span>][<span class="string">'upload_path'</span>].DS.$folderpath.DS.$prefix.$filename; <span class="comment">//缩略图的全路径</span></div><div class="line">        $save_fn = <span class="string">'image'</span>.$type;</div><div class="line">        $save_fn($dst_img,$small_path);</div><div class="line">        <span class="comment">// 关闭资源</span></div><div class="line">        imagedestroy($src_img);</div><div class="line">        imagedestroy($dst_img);</div><div class="line">        <span class="comment">// 返回缩略图保存路径</span></div><div class="line">        <span class="keyword">return</span> $folderpath.DS.$prefix.$filename;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20161007-1.html" itemprop="url">
                  PHP - 递归实现无限极联动
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-07T00:56:02+08:00" content="2016-10-07">
              2016-10-07
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20161007-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20161007-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="递归实现无限极联动"><a href="#递归实现无限极联动" class="headerlink" title="递归实现无限极联动"></a>递归实现无限极联动</h1><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">mysql_connect(<span class="string">'localhost'</span>,<span class="string">'root'</span>,<span class="string">'aa'</span>);</div><div class="line">mysql_select_db(<span class="string">'php6'</span>);</div><div class="line">mysql_query(<span class="string">'set names utf8'</span>);</div><div class="line"><span class="comment">//获取所有类别</span></div><div class="line">$sql=<span class="string">'select * from category'</span>;</div><div class="line">$rs=mysql_query($sql);</div><div class="line"><span class="comment">//将资源转成二维数组</span></div><div class="line">$list=<span class="keyword">array</span>();</div><div class="line"><span class="keyword">while</span>($rows=mysql_fetch_assoc($rs)) &#123;</div><div class="line">	$list[]=$rows;</div><div class="line">&#125;</div><div class="line"><span class="comment">/**</span></div><div class="line">*将二维数组按树形结构显示【递归】</div><div class="line">*<span class="doctag">@param</span> $list array 存放所有类别的二维数组</div><div class="line">*<span class="doctag">@param</span> $parentid int 在数组中查找属于某个父类的子级</div><div class="line">*<span class="doctag">@param</span> $deep int 元素的缩进深度</div><div class="line">*/</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">createTree</span><span class="params">($list,$parentid=<span class="number">0</span>,$deep=<span class="number">0</span>)</span> </span>&#123;</div><div class="line">	<span class="keyword">static</span> $tree=<span class="keyword">array</span>();	<span class="comment">//声明一个静态数组，这样在整个递归过程中一直存在</span></div><div class="line">	<span class="keyword">foreach</span>($list <span class="keyword">as</span> $rows) &#123;</div><div class="line">		<span class="keyword">if</span>($rows[<span class="string">'parentid'</span>]==$parentid)&#123;</div><div class="line">			$rows[<span class="string">'deep'</span>]=$deep;</div><div class="line">			$tree[]=$rows;</div><div class="line">			createTree($list,$rows[<span class="string">'cat_id'</span>],$deep+<span class="number">1</span>);</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">return</span> $tree;;</div><div class="line">&#125;</div><div class="line"><span class="comment">//测试</span></div><div class="line">$array=createTree($list);</div><div class="line"><span class="keyword">foreach</span>($array <span class="keyword">as</span> $rows) &#123;</div><div class="line">	<span class="comment">//str_repeat()：字符串重复</span></div><div class="line">	<span class="keyword">echo</span> str_repeat(<span class="string">'&amp;nbsp;'</span>,$rows[<span class="string">'deep'</span>]*<span class="number">20</span>),$rows[<span class="string">'cat_name'</span>],<span class="string">'&lt;br&gt;'</span>;</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h1 id="二级联动"><a href="#二级联动" class="headerlink" title="二级联动"></a>二级联动</h1><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="comment">//连接数据库</span></div><div class="line">mysql_connect(<span class="string">'localhost'</span>,<span class="string">'root'</span>,<span class="string">'aa'</span>);</div><div class="line">mysql_select_db(<span class="string">'php6'</span>);</div><div class="line">mysql_query(<span class="string">'set names utf8'</span>);</div><div class="line"><span class="comment">//获取第一级</span></div><div class="line">$sql=<span class="string">"select * from category where parentid=0"</span>;</div><div class="line">$rs1=mysql_query($sql);</div><div class="line"><span class="meta">?&gt;</span></div><div class="line">&lt;select name=<span class="string">""</span>&gt;</div><div class="line">	<span class="meta">&lt;?php</span></div><div class="line">	<span class="keyword">while</span>($rows1=mysql_fetch_assoc($rs1)):</div><div class="line">	<span class="meta">?&gt;</span></div><div class="line">		&lt;optgroup label=<span class="string">"&lt;?php echo $rows1['cat_name']?&gt;"</span>&gt;</div><div class="line">			<span class="meta">&lt;?php</span></div><div class="line">				$sql=<span class="string">"select * from category where parentid="</span>.$rows1[<span class="string">'cat_id'</span>];</div><div class="line">				$rs2=mysql_query($sql);</div><div class="line">				<span class="keyword">while</span>($rows2=mysql_fetch_assoc($rs2)):</div><div class="line">			<span class="meta">?&gt;</span></div><div class="line">				&lt;option value=<span class="string">"&lt;?php echo $rows2['cat_id']?&gt;"</span>&gt;<span class="meta">&lt;?php</span> <span class="keyword">echo</span> $rows2[<span class="string">'cat_name'</span>]<span class="meta">?&gt;</span>&lt;/option&gt;</div><div class="line">			<span class="meta">&lt;?php</span></div><div class="line">				<span class="keyword">endwhile</span>;</div><div class="line">			<span class="meta">?&gt;</span></div><div class="line">		&lt;/optgroup&gt;</div><div class="line">	<span class="meta">&lt;?php</span></div><div class="line">	<span class="keyword">endwhile</span>;</div><div class="line">	<span class="meta">?&gt;</span></div><div class="line">&lt;/select&gt;</div></pre></td></tr></table></figure>
<h1 id="三级联动"><a href="#三级联动" class="headerlink" title="三级联动"></a>三级联动</h1><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div></pre></td><td class="code"><pre><div class="line">&lt;script type=<span class="string">"text/javascript"</span>&gt;</div><div class="line"><span class="comment">/*</span></div><div class="line">*<span class="doctag">@param</span> cat1 int 一级的id</div><div class="line">*<span class="doctag">@param</span> cat2 int 二级的id</div><div class="line">*/</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">jump</span><span class="params">(cat1,cat2)</span> </span>&#123;</div><div class="line">	location.href=<span class="string">'?cat1='</span>+cat1+<span class="string">'&amp;cat2='</span>+cat2;</div><div class="line">&#125;</div><div class="line">&lt;/script&gt;</div><div class="line"><span class="meta">&lt;?php</span></div><div class="line">	mysql_connect(<span class="string">'localhost'</span>,<span class="string">'root'</span>,<span class="string">'aa'</span>);</div><div class="line">	mysql_select_db(<span class="string">'php6'</span>);</div><div class="line">	mysql_query(<span class="string">'set names utf8'</span>);</div><div class="line"></div><div class="line">	<span class="comment">//获取一级和二级的编号</span></div><div class="line">	$cat1=<span class="keyword">isset</span>($_GET[<span class="string">'cat1'</span>])?(int)$_GET[<span class="string">'cat1'</span>]:<span class="string">''</span>;	<span class="comment">//获取传递的一级编号</span></div><div class="line">	$cat2=<span class="keyword">isset</span>($_GET[<span class="string">'cat2'</span>])?(int)$_GET[<span class="string">'cat2'</span>]:<span class="string">''</span>;	<span class="comment">//获取传递的二级编号</span></div><div class="line"><span class="meta">?&gt;</span></div><div class="line">&lt;!--一级--&gt;</div><div class="line">&lt;select id=<span class="string">"cat1"</span> onchange=<span class="string">'jump(this.value,"")'</span>&gt;</div><div class="line">&lt;option value=<span class="string">""</span>&gt;---请选择---&lt;/option&gt;</div><div class="line"><span class="meta">&lt;?php</span></div><div class="line">	$sql=<span class="string">"select * from category where parentid=0"</span>;</div><div class="line">	$rs=mysql_query($sql);</div><div class="line">	<span class="keyword">while</span>($rows=mysql_fetch_assoc($rs)):</div><div class="line"><span class="meta">?&gt;</span></div><div class="line">	&lt;option value=<span class="string">"&lt;?php echo $rows['cat_id']?&gt;"</span> <span class="meta">&lt;?php</span> <span class="keyword">echo</span> $cat1==$rows[<span class="string">'cat_id'</span>]?<span class="string">'selected'</span>:<span class="string">''</span><span class="meta">?&gt;</span>&gt;<span class="meta">&lt;?php</span> <span class="keyword">echo</span> $rows[<span class="string">'cat_name'</span>]<span class="meta">?&gt;</span>&lt;/option&gt;</div><div class="line"><span class="meta">&lt;?php</span></div><div class="line">	<span class="keyword">endwhile</span>;</div><div class="line"><span class="meta">?&gt;</span>	</div><div class="line">&lt;/select&gt;</div><div class="line">&lt;!--二级--&gt;</div><div class="line">&lt;select id=<span class="string">"cat2"</span> onchange=<span class="string">'jump(document.getElementById("cat1").value,this.value)'</span>&gt;</div><div class="line">&lt;option value=<span class="string">""</span>&gt;---请选择---&lt;/option&gt;</div><div class="line"><span class="meta">&lt;?php</span></div><div class="line">	<span class="keyword">if</span>(<span class="keyword">isset</span>($_GET[<span class="string">'cat1'</span>])):</div><div class="line">		$sql=<span class="string">"select * from category where parentid=$cat1"</span>;</div><div class="line">		$rs=mysql_query($sql);</div><div class="line">		<span class="keyword">while</span>($rows=mysql_fetch_assoc($rs)):</div><div class="line"><span class="meta">?&gt;</span></div><div class="line">		&lt;option value=<span class="string">"&lt;?php echo $rows['cat_id']?&gt;"</span> <span class="meta">&lt;?php</span> <span class="keyword">echo</span> $cat2==$rows[<span class="string">'cat_id'</span>]?<span class="string">'selected'</span>:<span class="string">''</span><span class="meta">?&gt;</span>&gt;<span class="meta">&lt;?php</span> <span class="keyword">echo</span> $rows[<span class="string">'cat_name'</span>]<span class="meta">?&gt;</span>&lt;/option&gt;</div><div class="line"><span class="meta">&lt;?php</span></div><div class="line">		<span class="keyword">endwhile</span>;</div><div class="line">	<span class="keyword">endif</span>;</div><div class="line"><span class="meta">?&gt;</span></div><div class="line">&lt;/select&gt;</div><div class="line">&lt;select id=<span class="string">"cat3"</span>&gt;</div><div class="line">&lt;option value=<span class="string">""</span>&gt;---请选择---&lt;/option&gt;</div><div class="line"><span class="meta">&lt;?php</span></div><div class="line">	<span class="keyword">if</span>(!<span class="keyword">empty</span>($_GET[<span class="string">'cat2'</span>])):</div><div class="line">		$sql=<span class="string">"select * from category where parentid=$cat2"</span>;</div><div class="line">		$rs=mysql_query($sql);</div><div class="line">		<span class="keyword">while</span>($rows=mysql_fetch_assoc($rs)):</div><div class="line"><span class="meta">?&gt;</span></div><div class="line">		&lt;option value=<span class="string">"&lt;?php echo $rows['cat_id']?&gt;"</span> &gt;<span class="meta">&lt;?php</span> <span class="keyword">echo</span> $rows[<span class="string">'cat_name'</span>]<span class="meta">?&gt;</span>&lt;/option&gt;</div><div class="line"><span class="meta">&lt;?php</span></div><div class="line">		<span class="keyword">endwhile</span>;</div><div class="line">	<span class="keyword">endif</span>;</div><div class="line"><span class="meta">?&gt;</span></div><div class="line">&lt;/select&gt;</div></pre></td></tr></table></figure>
          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20161005-1.html" itemprop="url">
                  异步的JavaScript和XML
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-05T22:07:14+08:00" content="2016-10-05">
              2016-10-05
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20161005-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20161005-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="概念介绍"><a href="#概念介绍" class="headerlink" title="概念介绍"></a>概念介绍</h1><p>AJAX的全称<br>Asynchronous JavaScript and XML<br>异步的JavaScript和XML</p>
<p>作用：在无需重新加载整个网页的情况下，能够更新部分网页的技术<br>通过少量数据交换，实现异部局部更新</p>
<p>应用：社交软件，地图</p>
<p>操作步骤：<br>1、利用html+css来实现页面，表达信息；<br>2、用XMLHttpRequest和web服务器进行数据的异步交换<br>3、运营js操作DOM，实现动态局部刷新；</p>
<p>XMLHttpRequest对象的出现分割了同步和异步。XMLHttpRequest出现之前是同步的，出现之后是异步的。<br>同步：页面请求实时传给服务器，导致必填数据没有填的时候，要回到页面上重新从头填写，耗时长、客户体验差。<br>异步：在页面必填项写上必填选项，不用通过传给服务器判断必填内容是否已经填写完整，耗时短、用户体验强。</p>
<h1 id="HTTP请求"><a href="#HTTP请求" class="headerlink" title="HTTP请求"></a>HTTP请求</h1><p>一个完整地HTTP请求过程，通常有7个步骤<br>1.建立TCP连接<br>2.Web浏览器向Web服务器发送请求命令<br>3.Web浏览器发送请求头信息<br>4.Web服务器应答<br>5.Web服务器发送应答头信息<br>6.Web服务器向浏览器发送数据<br>7.Web服务器关闭TCP连接</p>
<p>一个HTTP请求一般由四部分组成<br>1.HTTP请求的方法或动作，比如是GET还是POST请求<br>2.正在请求的URL，总得知道请求的地址是什么吧<br>3.请求头，包含一些客户端环境信息，身份验证信息等<br>4.请求体，也就是请求正文，请求正文中可以包含客户提交的查询字符串信息，表单信息等等</p>
<p>一个HTTP响应一般由三部分组成<br>1.一个数字和文字组成的状态码，用来显示请求是成功还是失败<br>2.响应头，响应头也和请求头一样包含许多有用的信息，例如服务器类型、日期时间、内容类型和长度等<br>3.响应体，也就是响应正文</p>
<p>GET：</p>
<ul>
<li>一般用于信息获取</li>
<li>使用URL传递参数</li>
<li>对所发送信息的数量也有限制，一般在2000个字符</li>
</ul>
<p>POST：</p>
<ul>
<li>一般用于修改服务器上的资源</li>
<li>对所发送信息的数量无限制</li>
</ul>
<h1 id="HTTP状态码"><a href="#HTTP状态码" class="headerlink" title="HTTP状态码"></a>HTTP状态码</h1><p>HTTP状态码由3位数字构成，其中首位数字定义了状态码的类型：<br>1XX：信息类，表示收到Web浏览器请求，正在进一步的处理中。<br>2XX：成功，表示用户请求被正确接收，理解和处理，例如：200 OK<br>3XX：重定向，表示请求没有成功，客户必须采取进一步的动作<br>4XX：客户端错误，表示客户端提交的请求有错误，例如：400 NOT FOUND 意味着请求中所引起的文档不存在<br>5XX：服务器错误，表示服务器不能完成对请求的处理：如500</p>
<h1 id="XMLHttpRequest发送请求"><a href="#XMLHttpRequest发送请求" class="headerlink" title="XMLHttpRequest发送请求"></a>XMLHttpRequest发送请求</h1><p>var request = new XMLHttpRequset();<br><code>open(method,url,async)</code><br><code>send(string)</code></p>
<p>GET 发送请求</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">request.open(&apos;GET&apos;,&apos;get.php?id=55&apos;,true);</div><div class="line">request.send();</div></pre></td></tr></table></figure>
<p>POST 发送请求</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">request.open(&quot;POST&quot;,&quot;create.php&quot;,true);</div><div class="line">request.setRequestHeader(&quot;Content-type&quot;,&quot;application/x-www-form-urlencoded&quot;);</div><div class="line">request.send(&quot;name=uiste&amp;sex=man&quot;);</div></pre></td></tr></table></figure>
<h1 id="XMLHttpRequset取得响应"><a href="#XMLHttpRequset取得响应" class="headerlink" title="XMLHttpRequset取得响应"></a>XMLHttpRequset取得响应</h1><p>responseText：获得字符串形式的响应数据<br>responseXML： 获得XML形式的响应数据<br>status和statusText：以数字和文本形式返回HTTP状态码<br>getAllResponseHeader()：获取所有的响应报头<br>getResponseHeader()：查询响应中的某个字段的值</p>
<h1 id="readyState属性"><a href="#readyState属性" class="headerlink" title="readyState属性"></a>readyState属性</h1><p>0：请求未初始化，open还没有调用<br>1：服务器连接已建立，open已经调用了<br>2：请求已接收，也就是接收到头信息了<br>3：请求处理中，也就是接收到响应主体了<br>4：请求已完成，且响应已就绪，也就是响应完成了</p>
<h1 id="源码案例"><a href="#源码案例" class="headerlink" title="源码案例"></a>源码案例</h1><p><img src="http://7xwlfk.com1.z0.glb.clouddn.com/AJAX.png" alt="AJAX"></p>
<hr>
<h2 id="json"><a href="#json" class="headerlink" title="json"></a>json</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div></pre></td><td class="code"><pre><div class="line">&lt;script&gt;</div><div class="line"><span class="built_in">document</span>.getElementById(<span class="string">"search"</span>).onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; </div><div class="line">	<span class="keyword">var</span> request = <span class="keyword">new</span> XMLHttpRequest();</div><div class="line">	request.open(<span class="string">"GET"</span>, <span class="string">"serverjson.php?number="</span> + <span class="built_in">document</span>.getElementById(<span class="string">"keyword"</span>).value);</div><div class="line">	request.send();</div><div class="line">	request.onreadystatechange = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</div><div class="line">		<span class="keyword">if</span> (request.readyState===<span class="number">4</span>) &#123;</div><div class="line">			<span class="keyword">if</span> (request.status===<span class="number">200</span>) &#123; </div><div class="line">				<span class="keyword">var</span> data = <span class="built_in">JSON</span>.parse(request.responseText);</div><div class="line">				<span class="keyword">if</span> (data.success) &#123; </div><div class="line">					<span class="built_in">document</span>.getElementById(<span class="string">"searchResult"</span>).innerHTML = data.msg;</div><div class="line">				&#125; <span class="keyword">else</span> &#123;</div><div class="line">					<span class="built_in">document</span>.getElementById(<span class="string">"searchResult"</span>).innerHTML = <span class="string">"出现错误："</span> + data.msg;</div><div class="line">				&#125;</div><div class="line">			&#125; <span class="keyword">else</span> &#123;</div><div class="line">				alert(<span class="string">"发生错误："</span> + request.status);</div><div class="line">			&#125;</div><div class="line">		&#125; </div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="built_in">document</span>.getElementById(<span class="string">"save"</span>).onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; </div><div class="line">	<span class="keyword">var</span> request = <span class="keyword">new</span> XMLHttpRequest();</div><div class="line">	request.open(<span class="string">"POST"</span>, <span class="string">"serverjson.php"</span>);</div><div class="line">	<span class="keyword">var</span> data = <span class="string">"name="</span> + <span class="built_in">document</span>.getElementById(<span class="string">"staffName"</span>).value </div><div class="line">	                  + <span class="string">"&amp;number="</span> + <span class="built_in">document</span>.getElementById(<span class="string">"staffNumber"</span>).value </div><div class="line">	                  + <span class="string">"&amp;sex="</span> + <span class="built_in">document</span>.getElementById(<span class="string">"staffSex"</span>).value </div><div class="line">	                  + <span class="string">"&amp;job="</span> + <span class="built_in">document</span>.getElementById(<span class="string">"staffJob"</span>).value;</div><div class="line">	request.setRequestHeader(<span class="string">"Content-type"</span>,<span class="string">"application/x-www-form-urlencoded"</span>);</div><div class="line">	request.send(data);</div><div class="line">	request.onreadystatechange = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</div><div class="line">		<span class="keyword">if</span> (request.readyState===<span class="number">4</span>) &#123;</div><div class="line">			<span class="keyword">if</span> (request.status===<span class="number">200</span>) &#123; </div><div class="line">				<span class="keyword">var</span> data = <span class="built_in">JSON</span>.parse(request.responseText);</div><div class="line">				<span class="keyword">if</span> (data.success) &#123; </div><div class="line">					<span class="built_in">document</span>.getElementById(<span class="string">"createResult"</span>).innerHTML = data.msg;</div><div class="line">				&#125; <span class="keyword">else</span> &#123;</div><div class="line">					<span class="built_in">document</span>.getElementById(<span class="string">"createResult"</span>).innerHTML = <span class="string">"出现错误："</span> + data.msg;</div><div class="line">				&#125;</div><div class="line">			&#125; <span class="keyword">else</span> &#123;</div><div class="line">				alert(<span class="string">"发生错误："</span> + request.status);</div><div class="line">			&#125;</div><div class="line">		&#125; </div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line">&lt;<span class="regexp">/script&gt;</span></div></pre></td></tr></table></figure>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="comment">//设置页面内容是html编码格式是utf-8</span></div><div class="line">header(<span class="string">"Content-Type: text/plain;charset=utf-8"</span>); </div><div class="line"><span class="comment">//header("Content-Type: application/json;charset=utf-8"); </span></div><div class="line"><span class="comment">//header("Content-Type: text/xml;charset=utf-8"); </span></div><div class="line"><span class="comment">//header("Content-Type: text/html;charset=utf-8"); </span></div><div class="line"><span class="comment">//header("Content-Type: application/javascript;charset=utf-8"); </span></div><div class="line"></div><div class="line"><span class="comment">//定义一个多维数组，包含员工的信息，每条员工信息为一个数组</span></div><div class="line">$staff = <span class="keyword">array</span></div><div class="line">	(</div><div class="line">		<span class="keyword">array</span>(<span class="string">"name"</span> =&gt; <span class="string">"洪七"</span>, <span class="string">"number"</span> =&gt; <span class="string">"101"</span>, <span class="string">"sex"</span> =&gt; <span class="string">"男"</span>, <span class="string">"job"</span> =&gt; <span class="string">"总经理"</span>),</div><div class="line">		<span class="keyword">array</span>(<span class="string">"name"</span> =&gt; <span class="string">"郭靖"</span>, <span class="string">"number"</span> =&gt; <span class="string">"102"</span>, <span class="string">"sex"</span> =&gt; <span class="string">"男"</span>, <span class="string">"job"</span> =&gt; <span class="string">"开发工程师"</span>),</div><div class="line">		<span class="keyword">array</span>(<span class="string">"name"</span> =&gt; <span class="string">"黄蓉"</span>, <span class="string">"number"</span> =&gt; <span class="string">"103"</span>, <span class="string">"sex"</span> =&gt; <span class="string">"女"</span>, <span class="string">"job"</span> =&gt; <span class="string">"产品经理"</span>)</div><div class="line">	);</div><div class="line"></div><div class="line"><span class="comment">//判断如果是get请求，则进行搜索；如果是POST请求，则进行新建</span></div><div class="line"><span class="comment">//$_SERVER是一个超全局变量，在一个脚本的全部作用域中都可用，不用使用global关键字</span></div><div class="line"><span class="comment">//$_SERVER["REQUEST_METHOD"]返回访问页面使用的请求方法</span></div><div class="line"><span class="keyword">if</span> ($_SERVER[<span class="string">"REQUEST_METHOD"</span>] == <span class="string">"GET"</span>) &#123;</div><div class="line">	search();</div><div class="line">&#125; <span class="keyword">elseif</span> ($_SERVER[<span class="string">"REQUEST_METHOD"</span>] == <span class="string">"POST"</span>)&#123;</div><div class="line">	create();</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//通过员工编号搜索员工</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">search</span><span class="params">()</span></span>&#123;</div><div class="line">	<span class="comment">//检查是否有员工编号的参数</span></div><div class="line">	<span class="comment">//isset检测变量是否设置；empty判断值为否为空</span></div><div class="line">	<span class="comment">//超全局变量 $_GET 和 $_POST 用于收集表单数据</span></div><div class="line">	<span class="keyword">if</span> (!<span class="keyword">isset</span>($_GET[<span class="string">"number"</span>]) || <span class="keyword">empty</span>($_GET[<span class="string">"number"</span>])) &#123;</div><div class="line">		<span class="keyword">echo</span> <span class="string">'&#123;"success":false,"msg":"参数错误"&#125;'</span>;</div><div class="line">		<span class="keyword">return</span>;</div><div class="line">	&#125;</div><div class="line">	<span class="comment">//函数之外声明的变量拥有 Global 作用域，只能在函数以外进行访问。</span></div><div class="line">	<span class="comment">//global 关键词用于访问函数内的全局变量</span></div><div class="line">	<span class="keyword">global</span> $staff;</div><div class="line">	<span class="comment">//获取number参数</span></div><div class="line">	$number = $_GET[<span class="string">"number"</span>];</div><div class="line">	$result = <span class="string">'&#123;"success":false,"msg":"没有找到员工。"&#125;'</span>;</div><div class="line">	</div><div class="line">	<span class="comment">//遍历$staff多维数组，查找key值为number的员工是否存在，如果存在，则修改返回结果</span></div><div class="line">	<span class="keyword">foreach</span> ($staff <span class="keyword">as</span> $value) &#123;</div><div class="line">		<span class="keyword">if</span> ($value[<span class="string">"number"</span>] == $number) &#123;</div><div class="line">			$result = <span class="string">'&#123;"success":true,"msg":"找到员工：员工编号：'</span> . $value[<span class="string">"number"</span>] . </div><div class="line">							<span class="string">'，员工姓名：'</span> . $value[<span class="string">"name"</span>] . </div><div class="line">							<span class="string">'，员工性别：'</span> . $value[<span class="string">"sex"</span>] . </div><div class="line">							<span class="string">'，员工职位：'</span> . $value[<span class="string">"job"</span>] . <span class="string">'"&#125;'</span>;</div><div class="line">			<span class="keyword">break</span>;</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">    <span class="keyword">echo</span> $result;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//创建员工</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">create</span><span class="params">()</span></span>&#123;</div><div class="line">	<span class="comment">//判断信息是否填写完全</span></div><div class="line">	<span class="keyword">if</span> (!<span class="keyword">isset</span>($_POST[<span class="string">"name"</span>]) || <span class="keyword">empty</span>($_POST[<span class="string">"name"</span>])</div><div class="line">		|| !<span class="keyword">isset</span>($_POST[<span class="string">"number"</span>]) || <span class="keyword">empty</span>($_POST[<span class="string">"number"</span>])</div><div class="line">		|| !<span class="keyword">isset</span>($_POST[<span class="string">"sex"</span>]) || <span class="keyword">empty</span>($_POST[<span class="string">"sex"</span>])</div><div class="line">		|| !<span class="keyword">isset</span>($_POST[<span class="string">"job"</span>]) || <span class="keyword">empty</span>($_POST[<span class="string">"job"</span>])) &#123;</div><div class="line">		<span class="keyword">echo</span> <span class="string">'&#123;"success":false,"msg":"参数错误，员工信息填写不全"&#125;'</span>;</div><div class="line">		<span class="keyword">return</span>;</div><div class="line">	&#125;</div><div class="line">	<span class="comment">//<span class="doctag">TODO:</span> 获取POST表单数据并保存到数据库</span></div><div class="line">	</div><div class="line">	<span class="comment">//提示保存成功</span></div><div class="line">	<span class="keyword">echo</span> <span class="string">'&#123;"success":true,"msg":"员工：'</span> . $_POST[<span class="string">"name"</span>] . <span class="string">' 信息保存成功！"&#125;'</span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<hr>
<h2 id="jQuery"><a href="#jQuery" class="headerlink" title="jQuery"></a>jQuery</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line">&lt;script&gt;</div><div class="line">$(<span class="built_in">document</span>).ready(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; </div><div class="line">	$(<span class="string">"#search"</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; </div><div class="line">		$.ajax(&#123; </div><div class="line">		    type: <span class="string">"GET"</span>, 	</div><div class="line">			url: <span class="string">"http://127.0.0.1:8080/ajaxdemo/serverjson2.php?number="</span> + $(<span class="string">"#keyword"</span>).val(),</div><div class="line">			dataType: <span class="string">"json"</span>,</div><div class="line">			success: <span class="function"><span class="keyword">function</span>(<span class="params">data</span>) </span>&#123;</div><div class="line">				<span class="keyword">if</span> (data.success) &#123; </div><div class="line">					$(<span class="string">"#searchResult"</span>).html(data.msg);</div><div class="line">				&#125; <span class="keyword">else</span> &#123;</div><div class="line">					$(<span class="string">"#searchResult"</span>).html(<span class="string">"出现错误："</span> + data.msg);</div><div class="line">				&#125;  </div><div class="line">			&#125;,</div><div class="line">			error: <span class="function"><span class="keyword">function</span>(<span class="params">jqXHR</span>)</span>&#123;     </div><div class="line">			   alert(<span class="string">"发生错误："</span> + jqXHR.status);  </div><div class="line">			&#125;,     </div><div class="line">		&#125;);</div><div class="line">	&#125;);</div><div class="line">	$(<span class="string">"#save"</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; </div><div class="line">		$.ajax(&#123; </div><div class="line">		    type: <span class="string">"POST"</span>, 	</div><div class="line">			url: <span class="string">"serverjson.php"</span>,</div><div class="line">			data: &#123;</div><div class="line">				name: $(<span class="string">"#staffName"</span>).val(), </div><div class="line">				number: $(<span class="string">"#staffNumber"</span>).val(), </div><div class="line">				sex: $(<span class="string">"#staffSex"</span>).val(), </div><div class="line">				job: $(<span class="string">"#staffJob"</span>).val()</div><div class="line">			&#125;,</div><div class="line">			dataType: <span class="string">"json"</span>,</div><div class="line">			success: <span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</div><div class="line">				<span class="keyword">if</span> (data.success) &#123; </div><div class="line">					$(<span class="string">"#createResult"</span>).html(data.msg);</div><div class="line">				&#125; <span class="keyword">else</span> &#123;</div><div class="line">					$(<span class="string">"#createResult"</span>).html(<span class="string">"出现错误："</span> + data.msg);</div><div class="line">				&#125;  </div><div class="line">			&#125;,</div><div class="line">			error: <span class="function"><span class="keyword">function</span>(<span class="params">jqXHR</span>)</span>&#123;     </div><div class="line">			   alert(<span class="string">"发生错误："</span> + jqXHR.status);  </div><div class="line">			&#125;,     </div><div class="line">		&#125;);</div><div class="line">	&#125;);</div><div class="line">&#125;);</div><div class="line"><span class="xml"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div></pre></td><td class="code"><pre><div class="line">&lt;?php</div><div class="line">//设置页面内容是html编码格式是utf-8</div><div class="line">//header(&quot;Content-Type: text/plain;charset=utf-8&quot;); </div><div class="line">header(&apos;Access-Control-Allow-Origin:*&apos;);</div><div class="line">header(&apos;Access-Control-Allow-Methods:POST,GET&apos;);</div><div class="line">header(&apos;Access-Control-Allow-Credentials:true&apos;); </div><div class="line">header(&quot;Content-Type: application/json;charset=utf-8&quot;); </div><div class="line">//header(&quot;Content-Type: text/xml;charset=utf-8&quot;); </div><div class="line">//header(&quot;Content-Type: text/html;charset=utf-8&quot;); </div><div class="line">//header(&quot;Content-Type: application/javascript;charset=utf-8&quot;); </div><div class="line"></div><div class="line">//定义一个多维数组，包含员工的信息，每条员工信息为一个数组</div><div class="line">$staff = array</div><div class="line">	(</div><div class="line">		array(&quot;name&quot; =&gt; &quot;洪七&quot;, &quot;number&quot; =&gt; &quot;101&quot;, &quot;sex&quot; =&gt; &quot;男&quot;, &quot;job&quot; =&gt; &quot;总经理&quot;),</div><div class="line">		array(&quot;name&quot; =&gt; &quot;郭靖&quot;, &quot;number&quot; =&gt; &quot;102&quot;, &quot;sex&quot; =&gt; &quot;男&quot;, &quot;job&quot; =&gt; &quot;开发工程师&quot;),</div><div class="line">		array(&quot;name&quot; =&gt; &quot;黄蓉&quot;, &quot;number&quot; =&gt; &quot;103&quot;, &quot;sex&quot; =&gt; &quot;女&quot;, &quot;job&quot; =&gt; &quot;产品经理&quot;)</div><div class="line">	);</div><div class="line"></div><div class="line">//判断如果是get请求，则进行搜索；如果是POST请求，则进行新建</div><div class="line">//$_SERVER是一个超全局变量，在一个脚本的全部作用域中都可用，不用使用global关键字</div><div class="line">//$_SERVER[&quot;REQUEST_METHOD&quot;]返回访问页面使用的请求方法</div><div class="line">if ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;GET&quot;) &#123;</div><div class="line">	search();</div><div class="line">&#125; elseif ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;)&#123;</div><div class="line">	create();</div><div class="line">&#125;</div><div class="line"></div><div class="line">//通过员工编号搜索员工</div><div class="line">function search()&#123;</div><div class="line">	//检查是否有员工编号的参数</div><div class="line">	//isset检测变量是否设置；empty判断值为否为空</div><div class="line">	//超全局变量 $_GET 和 $_POST 用于收集表单数据</div><div class="line">	if (!isset($_GET[&quot;number&quot;]) || empty($_GET[&quot;number&quot;])) &#123;</div><div class="line">		echo &apos;&#123;&quot;success&quot;:false,&quot;msg&quot;:&quot;参数错误&quot;&#125;&apos;;</div><div class="line">		return;</div><div class="line">	&#125;</div><div class="line">	//函数之外声明的变量拥有 Global 作用域，只能在函数以外进行访问。</div><div class="line">	//global 关键词用于访问函数内的全局变量</div><div class="line">	global $staff;</div><div class="line">	//获取number参数</div><div class="line">	$number = $_GET[&quot;number&quot;];</div><div class="line">	$result = &apos;&#123;&quot;success&quot;:false,&quot;msg&quot;:&quot;没有找到员工。&quot;&#125;&apos;;</div><div class="line">	</div><div class="line">	//遍历$staff多维数组，查找key值为number的员工是否存在，如果存在，则修改返回结果</div><div class="line">	foreach ($staff as $value) &#123;</div><div class="line">		if ($value[&quot;number&quot;] == $number) &#123;</div><div class="line">			$result = &apos;&#123;&quot;success&quot;:true,&quot;msg&quot;:&quot;找到员工：员工编号：&apos; . $value[&quot;number&quot;] . </div><div class="line">							&apos;，员工姓名：&apos; . $value[&quot;name&quot;] . </div><div class="line">							&apos;，员工性别：&apos; . $value[&quot;sex&quot;] . </div><div class="line">							&apos;，员工职位：&apos; . $value[&quot;job&quot;] . &apos;&quot;&#125;&apos;;</div><div class="line">			break;</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">    echo $result;</div><div class="line">&#125;</div><div class="line"></div><div class="line">//创建员工</div><div class="line">function create()&#123;</div><div class="line">	//判断信息是否填写完全</div><div class="line">	if (!isset($_POST[&quot;name&quot;]) || empty($_POST[&quot;name&quot;])</div><div class="line">		|| !isset($_POST[&quot;number&quot;]) || empty($_POST[&quot;number&quot;])</div><div class="line">		|| !isset($_POST[&quot;sex&quot;]) || empty($_POST[&quot;sex&quot;])</div><div class="line">		|| !isset($_POST[&quot;job&quot;]) || empty($_POST[&quot;job&quot;])) &#123;</div><div class="line">		echo &apos;&#123;&quot;success&quot;:false,&quot;msg&quot;:&quot;参数错误，员工信息填写不全&quot;&#125;&apos;;</div><div class="line">		return;</div><div class="line">	&#125;</div><div class="line">	//TODO: 获取POST表单数据并保存到数据库</div><div class="line">	</div><div class="line">	//提示保存成功</div><div class="line">	echo &apos;&#123;&quot;success&quot;:true,&quot;msg&quot;:&quot;员工：&apos; . $_POST[&quot;name&quot;] . &apos; 信息保存成功！&quot;&#125;&apos;;</div><div class="line">&#125;</div><div class="line"></div><div class="line">?&gt;</div></pre></td></tr></table></figure>
<hr>
<h2 id="jQuery-json"><a href="#jQuery-json" class="headerlink" title="jQuery-json"></a>jQuery-json</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div></pre></td><td class="code"><pre><div class="line">&lt;script&gt;</div><div class="line">$(document).ready(function()&#123; </div><div class="line">	$(&quot;#search&quot;).click(function()&#123; </div><div class="line">		$.ajax(&#123; </div><div class="line">		    type: &quot;GET&quot;, 	</div><div class="line">			url: &quot;http://127.0.0.1:8000/ajaxdemo/serverjsonp.php?number=&quot; + $(&quot;#keyword&quot;).val(),</div><div class="line">			dataType: &quot;jsonp&quot;,</div><div class="line">			jsonp: &quot;callback&quot;,</div><div class="line">			success: function(data) &#123;</div><div class="line">				if (data.success) &#123;</div><div class="line">					$(&quot;#searchResult&quot;).html(data.msg);</div><div class="line">				&#125; else &#123;</div><div class="line">					$(&quot;#searchResult&quot;).html(&quot;出现错误：&quot; + data.msg);</div><div class="line">				&#125;  </div><div class="line">			&#125;,</div><div class="line">			error: function(jqXHR)&#123;     </div><div class="line">			   alert(&quot;发生错误：&quot; + jqXHR.status);  </div><div class="line">			&#125;,     </div><div class="line">		&#125;);</div><div class="line">	&#125;);</div><div class="line">	</div><div class="line">	$(&quot;#save&quot;).click(function()&#123; </div><div class="line">		$.ajax(&#123; </div><div class="line">		    type: &quot;POST&quot;, 	</div><div class="line">			url: &quot;http://127.0.0.1:8000/ajaxdemo/serverjsonp.php&quot;,</div><div class="line">			data: &#123;</div><div class="line">				name: $(&quot;#staffName&quot;).val(), </div><div class="line">				number: $(&quot;#staffNumber&quot;).val(), </div><div class="line">				sex: $(&quot;#staffSex&quot;).val(), </div><div class="line">				job: $(&quot;#staffJob&quot;).val()</div><div class="line">			&#125;,</div><div class="line">			dataType: &quot;json&quot;,</div><div class="line">			success: function(data)&#123;</div><div class="line">				if (data.success) &#123; </div><div class="line">					$(&quot;#createResult&quot;).html(data.msg);</div><div class="line">				&#125; else &#123;</div><div class="line">					$(&quot;#createResult&quot;).html(&quot;出现错误：&quot; + data.msg);</div><div class="line">				&#125;  </div><div class="line">			&#125;,</div><div class="line">			error: function(jqXHR)&#123;     </div><div class="line">			   alert(&quot;发生错误：&quot; + jqXHR.status);  </div><div class="line">			&#125;,     </div><div class="line">		&#125;);</div><div class="line">	&#125;);</div><div class="line">&#125;);</div><div class="line">&lt;/script&gt;</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div></pre></td><td class="code"><pre><div class="line">&lt;?php</div><div class="line">//设置页面内容是html编码格式是utf-8</div><div class="line">//header(&quot;Content-Type: text/plain;charset=utf-8&quot;); </div><div class="line">header(&quot;Content-Type: application/json;charset=utf-8&quot;); </div><div class="line">//header(&quot;Content-Type: text/xml;charset=utf-8&quot;); </div><div class="line">//header(&quot;Content-Type: text/html;charset=utf-8&quot;); </div><div class="line">//header(&quot;Content-Type: application/javascript;charset=utf-8&quot;); </div><div class="line"></div><div class="line">//定义一个多维数组，包含员工的信息，每条员工信息为一个数组</div><div class="line">$staff = array</div><div class="line">	(</div><div class="line">		array(&quot;name&quot; =&gt; &quot;洪七&quot;, &quot;number&quot; =&gt; &quot;101&quot;, &quot;sex&quot; =&gt; &quot;男&quot;, &quot;job&quot; =&gt; &quot;总经理&quot;),</div><div class="line">		array(&quot;name&quot; =&gt; &quot;郭靖&quot;, &quot;number&quot; =&gt; &quot;102&quot;, &quot;sex&quot; =&gt; &quot;男&quot;, &quot;job&quot; =&gt; &quot;开发工程师&quot;),</div><div class="line">		array(&quot;name&quot; =&gt; &quot;黄蓉&quot;, &quot;number&quot; =&gt; &quot;103&quot;, &quot;sex&quot; =&gt; &quot;女&quot;, &quot;job&quot; =&gt; &quot;产品经理&quot;)</div><div class="line">	);</div><div class="line"></div><div class="line">//判断如果是get请求，则进行搜索；如果是POST请求，则进行新建</div><div class="line">//$_SERVER是一个超全局变量，在一个脚本的全部作用域中都可用，不用使用global关键字</div><div class="line">//$_SERVER[&quot;REQUEST_METHOD&quot;]返回访问页面使用的请求方法</div><div class="line">if ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;GET&quot;) &#123;</div><div class="line">	search();</div><div class="line">&#125; elseif ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;)&#123;</div><div class="line">	create();</div><div class="line">&#125;</div><div class="line"></div><div class="line">//通过员工编号搜索员工</div><div class="line">function search()&#123;</div><div class="line">	$jsonp = $_GET[&quot;callback&quot;];</div><div class="line">	//检查是否有员工编号的参数</div><div class="line">	//isset检测变量是否设置；empty判断值为否为空</div><div class="line">	//超全局变量 $_GET 和 $_POST 用于收集表单数据</div><div class="line">	if (!isset($_GET[&quot;number&quot;]) || empty($_GET[&quot;number&quot;])) &#123;</div><div class="line">		echo $jsonp . &apos;(&#123;&quot;success&quot;:false,&quot;msg&quot;:&quot;参数错误&quot;&#125;)&apos;;</div><div class="line">		return;</div><div class="line">	&#125;</div><div class="line">	//函数之外声明的变量拥有 Global 作用域，只能在函数以外进行访问。</div><div class="line">	//global 关键词用于访问函数内的全局变量</div><div class="line">	global $staff;</div><div class="line">	//获取number参数</div><div class="line">	$number = $_GET[&quot;number&quot;];</div><div class="line">	$result = $jsonp . &apos;(&#123;&quot;success&quot;:false,&quot;msg&quot;:&quot;没有找到员工。&quot;&#125;)&apos;;</div><div class="line">	</div><div class="line">	//遍历$staff多维数组，查找key值为number的员工是否存在，如果存在，则修改返回结果</div><div class="line">	foreach ($staff as $value) &#123;</div><div class="line">		if ($value[&quot;number&quot;] == $number) &#123;</div><div class="line">			$result = $jsonp . &apos;(&#123;&quot;success&quot;:true,&quot;msg&quot;:&quot;找到员工：员工编号：&apos; . $value[&quot;number&quot;] .</div><div class="line">							&apos;，员工姓名：&apos; . $value[&quot;name&quot;] . </div><div class="line">							&apos;，员工性别：&apos; . $value[&quot;sex&quot;] . </div><div class="line">							&apos;，员工职位：&apos; . $value[&quot;job&quot;] . &apos;&quot;&#125;)&apos;;</div><div class="line">			break;</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">    echo $result;</div><div class="line">&#125;</div><div class="line"></div><div class="line">//创建员工</div><div class="line">function create()&#123;</div><div class="line">	//判断信息是否填写完全</div><div class="line">	if (!isset($_POST[&quot;name&quot;]) || empty($_POST[&quot;name&quot;])</div><div class="line">		|| !isset($_POST[&quot;number&quot;]) || empty($_POST[&quot;number&quot;])</div><div class="line">		|| !isset($_POST[&quot;sex&quot;]) || empty($_POST[&quot;sex&quot;])</div><div class="line">		|| !isset($_POST[&quot;job&quot;]) || empty($_POST[&quot;job&quot;])) &#123;</div><div class="line">		echo &apos;&#123;&quot;success&quot;:false,&quot;msg&quot;:&quot;参数错误，员工信息填写不全&quot;&#125;&apos;;</div><div class="line">		return;</div><div class="line">	&#125;</div><div class="line">	//TODO: 获取POST表单数据并保存到数据库</div><div class="line">	</div><div class="line">	//提示保存成功</div><div class="line">	echo &apos;&#123;&quot;success&quot;:true,&quot;msg&quot;:&quot;员工：&apos; . $_POST[&quot;name&quot;] . &apos; 信息保存成功！&quot;&#125;&apos;;</div><div class="line">&#125;</div><div class="line"></div><div class="line">?&gt;</div></pre></td></tr></table></figure>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
  </section>

  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/2/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/">1</a><a class="page-number" href="/page/2/">2</a><span class="page-number current">3</span><a class="page-number" href="/page/4/">4</a><span class="space">&hellip;</span><a class="page-number" href="/page/14/">14</a><a class="extend next" rel="next" href="/page/4/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel  sidebar-panel-active ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="uiste" />
          <p class="site-author-name" itemprop="name">uiste</p>
          <p class="site-description motion-element" itemprop="description">Stay Hungry，Stay Foolish</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">70</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">分类</span>
              
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">55</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/uiste" target="_blank" rel="external nofollow" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/uiste" target="_blank" rel="external nofollow" title="微博">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  微博
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.zhihu.com/people/uiste" target="_blank" rel="external nofollow" title="知乎">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  知乎
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.uiste.com" title="uiste 个人博客" target="_blank">uiste 个人博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://uiste.github.io" title="uiste 技术博客" target="_blank">uiste 技术博客</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">uiste</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io" rel="external nofollow">Hexo</a> 趋势动力
</div>
<!--站长统计-->
<script src="https://s95.cnzz.com/z_stat.php?id=1259894121&web_id=1259894121" language="JavaScript"></script>
<!--<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div> -->
&nbsp;&nbsp;&nbsp;本站总点击 <span id="busuanzi_value_site_pv"></span> 次
&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;您是第 <span id="busuanzi_value_site_uv"></span> 位访客

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>

<script>
(function(){
    var bp = document.createElement('script');
    bp.src = '//push.zhanzhang.baidu.com/push.js';
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"uiste"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });

                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

</body>
</html>
